package com.powernobug.servlet;

import com.powernobug.bean.vo.BaseRespVo;
import com.powernobug.util.DispatchUtil;
import com.powernobug.util.JsonUtil;
import org.apache.ibatis.exceptions.PersistenceException;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-16
 * @Description:
 */
@MultipartConfig
@WebServlet("/*")
public class CommonServlet extends HttpServlet {

    private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String uri = req.getRequestURI();
        String suffix = uri.substring(uri.lastIndexOf('/') + 1);
        String result = "";

        try {
            BaseRespVo baseRespVo = DispatchUtil.taskDispatcher(suffix, req, this);
            result = JsonUtil.writeJson(baseRespVo);
        }
        catch (NoSuchMethodException e) {
            result = JsonUtil.writeJson(BaseRespVo.errList( 404));
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            result = JsonUtil.writeJson(BaseRespVo.errList( 502));
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof PersistenceException || cause instanceof IllegalArgumentException) {}
                result = JsonUtil.writeJson(BaseRespVo.errList( 402));
            if (cause instanceof ClassCastException)
                result = JsonUtil.writeJson(BaseRespVo.errList( 403));
            e.printStackTrace();
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(result);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        process(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        process(req, resp);
    }
}
